import { apiInit } from '@/services'
import {
	IFetchNewsList,
	IFetchNoticesList,
	IFetchRegulationList,
} from '../../../type'
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useLoading } from '@/hooks/useLoading'
import { client } from '@/utils'
export default function useDetails() {
	const api = apiInit()
	const detailList = ref({})
	const defaultLoading = ref({ loading: false })

	const { getLoading, setLoading } = useLoading(defaultLoading)
	const fetchNewsList = async ({ page = {}, query = {} }: IFetchNewsList) => {
		setLoading(true)
		const { data, code } = await api.default.ListNewsPrivateV2POST({
			payload: { page, query },
		})
		setLoading(false)
		if (code === '000000') {
			const list: any = data
			list.rows.map((item: any, index: number) => {
				item.id = item.news_id
				return item
			})
			return list.rows
		}
	}
	const page = {
		page_index: 1,
		page_size: 5,
	}
	const query = {
		category_id: '',
		create_time: '',
		creator: '',
		end_time: '',
		title: '',
	}
	const router = useRouter()
	const toMore = () => {
		router.push({
			name: 'AttachmentCenter',
			query: { type: 'news' },
		})
	}
	// 新闻统计接口
	const newsCount = (id: string) => {
		api.default.CountHitsNewsPrivateV2POST({
			payload: {
				news_id: id,
			},
		})
	}
	const handeleDetail = (params: any) => {
		if (params.news_type === 1) {
			client.openWindow(params.external_link)
			// window.open(params.external_link)
		} else {
			router.push({
				name: 'AttachmentDetail',
				query: { type: 'news', id: params.id },
			})
		}
		newsCount(params.news_id)
	}
	const carouselData: any = ref([])
	const getCarousel = async () => {
		setLoading(true)
		const res = await api.default.ListCarouselPrivateV2POST({})
		if (res.code === '000000') {
			carouselData.value = res.data
		}
		setLoading(false)
	}
	onMounted(async () => {
		detailList.value = await fetchNewsList({ page, query })
		getCarousel()
		getMenuTitle()
	})
	//轮播图点击数统计
	const clickCarouselCountHandle = (carousel_id: any) => {
		api.default.CountHitsCarouselPrivateV2POST({
			payload: { carousel_id },
		})
	}
	// 轮播图点击事件
	const onCarousel = (params: any) => {
		clickCarouselCountHandle(params.carousel_id)
	}

	const MenuTitle: any = ref({})
	const local = localStorage.getItem('locale')?.slice(0, 2)
	const isShowIcon: any = ref(true)
	// 获取模块标题
	const getMenuTitle = async () => {
		const { data } = await api.portalExtend.POSTInfoModuleList({})
		for (let key in data) {
			if (data[key]?.module_id === 'NEWS') {
				MenuTitle.value = data[key].name
				isShowIcon.value = data[key].show_icon
			}
		}
	}

	return {
		fetchNewsList,
		detailList,
		toMore,
		handeleDetail,
		carouselData,
		getLoading,
		onCarousel,
		MenuTitle,
		local,
		isShowIcon,
	}
}
